<?PHP
  $template = new Template();
  $template->load("menu_edit");
  if($_POST['add']){
    if(trim($_POST['newtitle']) != ""){
      if(trim($_POST['newurl']) != ""){
	    $entry        = new MenuEntry();
	    $entry->menu  = $_GET['menu'];
	    $entry->title = $_POST['newtitle'];
	    $entry->type  = $_POST['type'];
		if($entry->type == 0){
	      $entry->href  = $_POST['newPage'];
		}
		else if($entry->type == 1){
	      $entry->href  = $_POST['newurl'];
		}
		else{
	      $entry->href  = $_POST['newMenu'];
		}
	    $res = $entry->save();
        if($res){
          $template->assign_var("MESSAGE",$GLOBALS['language']->getString("ENTRY_ADDED"));
        }
        else{
          $template->assign_var("MESSAGE",$GLOBALS['language']->getString("ENTRY_NOT_ADDED"));
        }
      }
      else{
        $template->assign_var("MESSAGE",$GLOBALS['language']->getString("ENTER_LINK_TARGET"));
      }
    }
    else{
        $template->assign_var("MESSAGE",$GLOBALS['language']->getString("ENTER_LINK_TITLE"));
    }
  }
  else if($_POST['save']){
    foreach($_POST as $param=>$value){
      if(strlen($param) >= 6){
        if(substr($param,-5,5) == "_href"){
          $entries[substr($param,0,-5)][href] = $value;
        }
        else if(strlen($param) >= 7 && substr($param,-6,6) == "_title"){
          $entries[substr($param,0,-6)][title] = $value;
        }
        else if(substr($param,-5,5) == "_type"){
          $entries[substr($param,0,-5)][type] = $value;
        }
      }
    }
    foreach($entries as $id=>$params){
	  $entry        = new MenuEntry();
	  $entry->id    = $id;
	  $entry->menu  = $_GET['menu'];
	  $entry->title = $params['title'];
	  $entry->href  = $params['href'];
	  $entry->type  = $params['type'];
	  $entry->save();
	}
  }
  else{
    foreach($_POST as $param=>$value){
      if(strlen($param) >= 8){
        if(substr($param,-7,7) == "_delete"){
          Menu::deleteEntry($GLOBALS['db']->EscapeString($_GET['menu']),
                            $GLOBALS['db']->EscapeString(substr($param,0,-7)));
        }
      }
    }
  }
  
  $template->assign_var("URL","index.php?page=menu-edit&menu=".urlencode($_GET['menu']));
  $template->assign_var("EDITABLEMENU",Menu::getEditableCode($GLOBALS['db']->EscapeString($_GET['menu'])));

  $selector = new MenueSelector();
  $selector->name  = 'newMenu';
  $selector->value = -1;
  $selector->style = 'width:200px;position:relative;left:-210px;visibility:hidden';
  $template->assign_var("MENUSELECTOR", $selector->getCode());

  $selector = new PageSelector();
  $selector->name  = 'newPage';
  $selector->value = -1;
  $selector->style = 'width:200px;position:relative;left:-415px;';
  $template->assign_var("PAGESELECTOR", $selector->getCode());
  
  $template->assign_var("MESSAGE","");
  $template->output();
?>